package org.yi.fc.controller.admin.content;

import java.util.Date;

import org.yi.fc.controller.base.BaseController;
import org.yi.fc.entity.FContentType;
import org.yi.fc.entity.FSysUser;

import com.jfinal.plugin.activerecord.Page;

public class ContentTypeController extends BaseController {
	
	public void index(){
		contentTypeList();
	}
	
	/**
	 * 文章类型
	 */
	public void contentTypeList(){
		
		int pageNumber = 0, pageSize = 15;
		try{
			pageNumber = this.getParaToInt("pageNumber");
			pageSize = this.getParaToInt("pageSize");
		}catch(NullPointerException e){
			pageNumber = 1;
			pageSize =15;
		}finally{
			FContentType fContentType = getModel(FContentType.class);
			Page<FContentType> page = fContentType.queryContentType(pageNumber,pageSize);
			
			setAttr("page", page).setAttr("fContentType", fContentType);
			render("contentType.html");
		}
		
		createToken("cms_token");
		render("contentType.html");
	}
	
	/**
	 * 添加（保存）文章类型
	 */
	public void saveContentType(){
		if(isPostMethod() ){
			if(!validateToken("cms_token")){
				addMessage("请不要重复提交");
				setAttr("msgStatus",ERROR);
			}else{
				try{
					FContentType fContentType = getModel(FContentType.class);
					
					if(fContentType.isTypeNameExisit()){
						addMessage("该类型名已存在！");
						setAttr("msgStatus",ERROR).setAttr("fContentType", fContentType);
						contentTypeList();
						return;
					}
					
					fContentType
					.set("create_time", new Date())
					.set("user_id", ( (FSysUser) getSessionAttr("f_sys_user") ).get("id") )
					.save();
					
					setAttr("fContentType", fContentType).setAttr("msgStatus",SUCCESS);
					addMessage("保存文章类型成功！");
					
				}catch(Exception e){
					e.printStackTrace();
					addMessage("保存文章类型失败" + e.getMessage());
					setAttr("msgStatus",ERROR);
					contentTypeList();
				}
			}
			
		}else{
			addMessage("文章类型提交失败，系统禁止使用" + getHttpMethod() + "方法访问！");
			setAttr("msgStatus",ERROR);
		}
		contentTypeList();
	}
	
	/**
	 * 修改类型的状态值
	 * 
	 */
	public void updateTypeStatus(){
		String msg = "" , msgStatus = "1";
		try{
			Long id = getParaToLong("typeId");
			FContentType.dao.findById(id).set("type_status", getPara("type_status")).update();
			msg = "修改文章类型的状态成功";
		}catch(Exception e){
			msg = "修改文章类型的状态失败! + \n" + e.getMessage() ;
			msgStatus = ERROR;
		}finally{
			addMessage(msg);
			setAttr("msgStatus", msgStatus);
			contentTypeList();
		}
	}
}
